package com.qining618.cms.config;

import com.qining618.common.exception.BusinessException;
import com.qining618.common.result.ApiResult;
import com.qining618.common.result.ErrorCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.MethodNotSupportedException;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author iqiao
 * @date 2019/8/18 0018.
 */
@Slf4j
@ControllerAdvice
public class CommonExceptionAdvice {

    @ResponseBody
    @ExceptionHandler(Exception.class)
    public ApiResult exceptionHandler(Exception e) {
        log.error(e.getMessage(), e);
        return ApiResult.failed(ErrorCode.FAILED);
    }

    @ResponseBody
    @ExceptionHandler(BusinessException.class)
    public ApiResult exceptionHandler(BusinessException e) {
        log.error(e.getMessage(), e);
        return ApiResult.failed(e.getErrorCode(), e.getMessage());
    }

    @ResponseBody
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ApiResult handleBindException(MethodArgumentNotValidException ex) {
        log.warn(ex.getMessage(), ex);
        FieldError fieldError = ex.getBindingResult().getFieldError();
        return ApiResult.failed(ErrorCode.BAD_REQUEST, fieldError.getDefaultMessage());
    }

    @ResponseBody
    @ExceptionHandler(BindException.class)
    public ApiResult handleBindException(BindException ex) {
        log.warn(ex.getMessage(), ex);
        FieldError fieldError = ex.getBindingResult().getFieldError();
        return ApiResult.failed(ErrorCode.BAD_REQUEST, fieldError.getDefaultMessage());
    }

    @ResponseBody
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public ApiResult handleBindException(HttpRequestMethodNotSupportedException ex) {
        log.error(ex.getMessage(), ex);
        return ApiResult.failed(ErrorCode.FAILED);
    }

    @ResponseBody
    @ExceptionHandler(MethodNotSupportedException.class)
    public ApiResult handleBindException(MethodNotSupportedException ex) {
        log.error(ex.getMessage(), ex);
        return ApiResult.failed(ErrorCode.FAILED);
    }
}
